import { Container, Grid, Card, CardContent, Typography, Box, Avatar, List, ListItem, ListItemText, Divider, LinearProgress, Button } from '@mui/material';
import { CloudUpload as CloudUploadIcon, CloudDownload as CloudDownloadIcon, Star as StarIcon, SwapHoriz as SwapHorizIcon } from '@mui/icons-material';
import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useAuth } from '../features/auth/AuthContext';
import { UserService, UserStats } from '../features/auth/services/UserService';
import { UserProfile, PointsTransaction } from '../features/auth/types';
import UploadTorrent from '../features/resources/components/UploadTorrent';
import React from 'react';
import { FriendsProvider } from '../features/friends/FriendsContext';
import FriendActionButton from '../features/friends/components/FriendActionButton';

// 格式化文件大小的辅助函数
const formatSize = (bytes: number): string => {
  if (bytes === 0) return '0 B';
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return parseFloat((bytes / Math.pow(1024, i)).toFixed(2)) + ' ' + sizes[i];
};

const Profile = () => {
  // 将字符串ID转换为数字
  const parseUserId = (id: string): number => {
    const numId = parseInt(id, 10);
    return isNaN(numId) ? 0 : numId;
  };
  const { username } = useParams<{ username: string }>();
  const { user } = useAuth();
  const [userData, setUserData] = useState<UserProfile | null>(null);
  const [pointsHistory, setPointsHistory] = useState<PointsTransaction[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [uploadDialogOpen, setUploadDialogOpen] = useState(false);
  const [currentPoints, setCurrentPoints] = useState<number | null>(null);
  const [userStats, setUserStats] = useState<UserStats | null>(null);

  useEffect(() => {
    const fetchUserData = async () => {
      try {
        setLoading(true);
        
        console.log('Profile页面加载，username参数:', username);
        
        // 如果URL中有用户名参数，则获取该用户的信息
        // 如果没有，则获取当前登录用户的信息
        if (username) {
          console.log('获取指定用户信息:', username);
          // 获取指定用户的信息
          const [profile, history] = await Promise.all([
            UserService.getUserProfile(username),
            UserService.getPointsHistory(username) // 这里仍然使用用户名，因为是查看其他用户的积分历史
          ]);
          
          setUserData(profile);
          setPointsHistory(history);
        } else {
          console.log('获取当前登录用户信息，包括积分');
          // 获取当前登录用户的信息
          const [profile, history] = await Promise.all([
            UserService.getCurrentUserProfile(),
            UserService.getPointsHistory(''), // 不再传递用户名，使用/auth/points/history接口
          ]);
          
          setUserData(profile);
          setPointsHistory(history);
        }
        
        // 无论是否有username参数，都获取当前用户积分
        console.log('获取当前用户积分');
        const points = await UserService.getCurrentUserPoints();
        setCurrentPoints(points);
        console.log('积分设置完成:', points);
        
        // 获取用户统计数据（上传量、下载量、分享率）
        const stats = await UserService.getUserStats();
        setUserStats(stats);
        console.log('用户统计数据设置完成:', stats);
        
        setError(null);
        
        // 用户帖子获取代码已删除
      } catch (err) {
        console.error('获取用户信息失败:', err);
        setError('获取用户信息失败');
      } finally {
        setLoading(false);
      }
    };

    fetchUserData();
  }, [username, user]);

  const handleUploadSuccess = () => {
    // 刷新用户数据
    if (userData?.username) {
      UserService.getUserProfile(userData.username)
        .then(profile => setUserData(profile))
        .catch(err => console.error('刷新用户数据失败:', err));
    }
    
    // 刷新积分数据
    UserService.getCurrentUserPoints()
      .then(points => setCurrentPoints(points))
      .catch(err => console.error('刷新积分数据失败:', err));
      
    // 刷新用户统计数据
    UserService.getUserStats()
      .then(stats => setUserStats(stats))
      .catch(err => console.error('刷新用户统计数据失败:', err));
  };

  // 帖子点击处理函数已删除

  if (loading) {
    return (
      <Container maxWidth="lg" sx={{ mt: 4 }}>
        <LinearProgress />
      </Container>
    );
  }

  if (error || !userData) {
    return (
      <Container>
        <Typography color="error">{error || '无法加载用户信息'}</Typography>
      </Container>
    );
  }

  return (
    <Container>
      <Grid container spacing={3}>
        {/* 用户基本信息卡片 */}
        <Grid item xs={12} md={4}>
          <Card>
            <CardContent>
              <Box display="flex" flexDirection="column" alignItems="center">
                <Avatar
                  src={userData.avatar}
                  alt={userData.username}
                  sx={{ width: 100, height: 100, mb: 2 }}
                />
                <Typography variant="h5" gutterBottom>
                  {userData.username}
                </Typography>
                <Typography color="textSecondary" gutterBottom>
                  {userData.email}
                </Typography>
                {/* 显示用户ID */}
                <Typography color="textSecondary" gutterBottom>
                  用户ID: {userData.id}
                </Typography>
                {/* 显示用户身份（角色） */}
                <Typography 
                  variant="subtitle1" 
                  color={userData.role === 'ADMIN' ? 'error' : 'primary'}
                  sx={{ mt: 1, fontWeight: 'bold' }}
                >
                  身份: {userData.role}
                </Typography>
                {currentPoints !== null && (
                  <Typography 
                    variant="subtitle1" 
                    color="primary"
                    sx={{ mt: 1, fontWeight: 'bold', display: 'flex', alignItems: 'center' }}
                  >
                    <StarIcon color="primary" sx={{ mr: 1, fontSize: '1rem' }} />
                    积分: {currentPoints}
                  </Typography>
                )}
                {user?.id !== userData.id && (
                  <Box sx={{ mt: 2 }}>
                    <FriendsProvider>
                      <FriendActionButton
                        userId={parseUserId(userData.id)}
                        onActionComplete={() => {
                          // 可以在这里添加好友操作完成后的刷新逻辑
                        }}
                      />
                    </FriendsProvider>
                  </Box>
                )}
                {/* 用户等级和经验条 */}
                <Box sx={{ mt: 2, width: '100%' }}>
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.5 }}>
                    <Typography variant="body2">
                      等级: {
                        (userData.experience || 0) > 100 ? 4 :
                        (userData.experience || 0) > 10 ? 3 :
                        (userData.experience || 0) > 1 ? 2 : 1
                      }
                    </Typography>
                    <Typography variant="body2">
                      经验值: {userData.experience || 0}
                    </Typography>
                  </Box>
                  <LinearProgress 
                    variant="determinate" 
                    value={Math.min(((userData.experience || 0) / 100) * 100, 100)} 
                    sx={{ height: 8, borderRadius: 5 }}
                  />
                </Box>
                
                {/* 用户上传下载统计 */}
                {userStats && (
                  <Box sx={{ mt: 3, width: '100%', bgcolor: 'background.paper', p: 2, borderRadius: 1 }}>
                    <Typography variant="subtitle1" gutterBottom sx={{ fontWeight: 'bold', mb: 2 }}>
                      传输统计
                    </Typography>
                    
                    <Box sx={{ display: 'flex', alignItems: 'center', mb: 1.5 }}>
                      <CloudUploadIcon color="success" sx={{ mr: 1 }} />
                      <Typography variant="body2">
                        上传量: {formatSize(userStats.uploadBytes)}
                      </Typography>
                    </Box>
                    
                    <Box sx={{ display: 'flex', alignItems: 'center', mb: 1.5 }}>
                      <CloudDownloadIcon color="info" sx={{ mr: 1 }} />
                      <Typography variant="body2">
                        下载量: {formatSize(userStats.downloadBytes)}
                      </Typography>
                    </Box>
                    
                    <Box sx={{ display: 'flex', alignItems: 'center' }}>
                      <SwapHorizIcon color="warning" sx={{ mr: 1 }} />
                      <Typography variant="body2">
                        分享率: {userStats.ratio.toFixed(2)}
                      </Typography>
                    </Box>
                    
                    <Typography variant="caption" color="textSecondary" sx={{ mt: 1, display: 'block' }}>
                      最后做种更新: {new Date(userStats.lastSeedingUpdate).toLocaleString()}
                    </Typography>
                  </Box>
                )}
                
                {/* 用户邀请码 */}
                <Box sx={{ mt: 2, width: '100%' }}>
                  <Typography variant="body2" gutterBottom>邀请码:</Typography>
                  <Typography 
                    variant="body1" 
                    sx={{ 
                      p: 1, 
                      bgcolor: 'background.paper', 
                      border: '1px dashed grey.500',
                      borderRadius: 1,
                      fontFamily: 'monospace',
                      wordBreak: 'break-all'
                    }}
                  >
                    {userData.passkey || '暂无邀请码'}
                  </Typography>
                </Box>
              </Box>
            </CardContent>
          </Card>
        </Grid>

        {/* 用户数据统计卡片已删除 */}
        <Grid item xs={12} md={8}>
          {/* 帖子展示模块已删除 */}

          {/* 积分历史记录 */}
          <Card sx={{ mt: 2 }}>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                积分历史
              </Typography>
              <List>
                {pointsHistory.map((transaction) => (
                  <React.Fragment key={transaction.id}>
                    <ListItem>
                      <ListItemText
                        primary={transaction.description}
                        secondary={
                          <>
                            <Typography component="span" variant="body2" color="textSecondary">
                              {new Date(transaction.createdAt).toLocaleString()}
                            </Typography>
                            <Typography
                              component="span"
                              variant="body2"
                              color={transaction.points > 0 ? 'success.main' : 'error.main'}
                              sx={{ ml: 2 }}
                            >
                              {transaction.points > 0 ? '+' : ''}{transaction.points}
                            </Typography>
                          </>
                        }
                      />
                    </ListItem>
                    <Divider />
                  </React.Fragment>
                ))}
              </List>
            </CardContent>
          </Card>
        </Grid>
      </Grid>


      {/* 上传种子对话框 */}
      <UploadTorrent
        open={uploadDialogOpen}
        onClose={() => setUploadDialogOpen(false)}
        onUploadSuccess={handleUploadSuccess}
      />
    </Container>
  );
};

export default Profile;